//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Discussions.Components;

namespace CommunityServer.Discussions.Controls {

    // *********************************************************************
    //  ThreadView
    //
    /// <summary>
    /// This server control is used to display top level threads. Note, a thread
    /// is a post with more information. The Thread class inherits from the Post
    /// class.
    /// </summary>
    /// 
    // ********************************************************************/
    public class ThreadRepeater : Repeater {
        #region Member variables and constructor

        CSContext csContext = CSContext.Current;
        internal Forum forum;
        ThreadViewMode mode = ThreadViewMode.Active;
		DateTime threadsNewerThan = DateTime.MinValue;
		SortThreadsBy sortBy = SortThreadsBy.LastPost;
		SortOrder sortOrder = SortOrder.Descending;
        int forumID = -1;
        int itemsToDisplayCount = 10;
        ThreadSet threadSet;
        #endregion

        protected override void Render(HtmlTextWriter writer) {
            Bind();

			if (threadSet != null && threadSet.HasResults)
				base.Render (writer);
        }

        #region Event Handlers


        #region Threads_ItemDataBound
        /// <summary>
        /// Added to handle Username displaying
        /// </summary>
        protected void Threads_ItemDataBound (Object Sender, RepeaterItemEventArgs e) {
            Thread thread = e.Item.DataItem as Thread;
            if (thread == null)
                return;
            
            bool isAnonymousPostingEnabled = thread.IsAnonymousPost && 
                ForumConfiguration.Instance().EnableUserPostingAsAnonymous &&
                thread.Forum.EnableAnonymousPostingForUsers;

            switch (e.Item.ItemType) {
                case  ListItemType.Item:
                case  ListItemType.AlternatingItem:
                    Label userName = e.Item.FindControl( "UsernameLink" ) as Label;
                    if (userName != null) {
                        userName.Text = Formatter.FormatUsername( thread.AuthorID, thread.Username, isAnonymousPostingEnabled, true, thread.ThreadShouldBeIgnored ); 
                    }

                    ThreadStatusImage statusImage = e.Item.FindControl( "ThreadItemStatusImage" ) as ThreadStatusImage;
                    if (statusImage != null && 
                        forum != null &&
                        !forum.EnableThreadStatus) {
                        //statusImage.ThreadStatus = ThreadStatus.NotSet;
                        statusImage.Visible = false;
                    }
                    break;
            }
        }
        #endregion

        #endregion

        #region Databinding

        public void Bind() {
            
            #region Load forum details by ThreadViewMode
            // Load forum details by ThreadViewMode
            //
            try {
                switch (this.ThreadViewMode) {
                    case ThreadViewMode.Active:                        
                    case ThreadViewMode.Unanswered:
					case ThreadViewMode.Videos:
                    case ThreadViewMode.NotRead:
                        if (ForumID > 0)
                            forum = Forums.GetForum( ForumID, true, true );
                        else
                            forum = new Forum( ForumID);
                        break;

                    default:
                        // Don't need filter when viewing a forum by default
                        if (ForumID > 0) {
                            forum = Forums.GetForum( ForumID, true, true );
                            Permissions.AccessCheck( forum, Permission.View, csContext.User );

                        }
                        break;
                }
            } 
            catch {
            }
            #endregion

            #region Check user's permissions
            // Check user's permissions on forum.
            // Also set new post button.
            //
            if (this.ThreadViewMode != ThreadViewMode.MyForums) {
                User user = csContext.User;
                if( forum.SectionID > 0 ) {
                    // TODO: Rollback to initial approach after permissions on 
                    // subforums are implemented.
                    //
                    // Note: This is a temporary solution untill permissions on subforums 
                    // are handled properly.
                    ForumPermission p = null;

                    if (forum.ParentID > 0) {
                        // Lookup for parent forum and verify credentials against it
                        //
                        Section parentSection = Forums.GetTopmostParentSection( forum.ParentID );
                        if (parentSection == null)
                            throw new CSException( CSExceptionType.AccessDenied );

                        p = parentSection.ResolvePermission( user ) as ForumPermission;
                    } 
                    else {
                        // No subforums
                        //
                        p = forum.ResolvePermission( user ) as ForumPermission;
                    }
                                            

                }
            }
            else
            {
                if(csContext.User.IsAnonymous)
                {
                    this.Visible = false;
                    return;
                }
            }
            #endregion

            #region Get a populated ThreadSet
            // Get a populated thread set
            //
            if ((forum != null) && (forum.SectionID > 0))
                forumID = forum.SectionID;
            else
                if (this.ThreadViewMode != ThreadViewMode.PrivateMessages)
                forumID = ForumID;

            ForumThreadQuery query = new ForumThreadQuery();
            query.ForumID = forumID;
            query.PageIndex = 0;
            query.PageSize = ItemsToDisplayCount;
			query.ThreadsNewerThan = this.ThreadsNewerThan;
            query.SortBy = this.SortThreadsBy;
            query.Order = this.SortOrder;

            switch (this.ThreadViewMode) {
                case ThreadViewMode.Active:
                    query.ActiveTopics = true;
                    threadSet = Threads.GetThreads(query);

                    break;

                case ThreadViewMode.Unanswered:    
                    
                    query.UnAnsweredOnly = true;
                    threadSet = Threads.GetThreads(query);

                    break;

                case ThreadViewMode.NotRead:

                    query.ThreadsNewerThan = DateTime.Now.AddDays(-ForumConfiguration.Instance().DaysPostMarkedAsRead);
                    threadSet = Threads.GetThreads(query);

                    break;
                
                case ThreadViewMode.MyForums:

                    query.UserFilter = ThreadUsersFilter.HideTopicsParticipatedIn;
                    threadSet = Threads.GetThreads(query);

                    break;
                
                case ThreadViewMode.PrivateMessages:
                    query.ForumID = 0;
                    threadSet = Threads.GetThreads(query);

                    break;

				case ThreadViewMode.Videos:
					query.PostMedia = PostMediaType.Video;
					threadSet = Threads.GetThreads(query);

					break;

                default:
                    if (forumID > 0) {
                        threadSet = Threads.GetThreads(query);
                    }   

                    break;
            }

            // Do we have posts to display?
            //
            if (threadSet.Threads.Count > 0) {
                DataSource = threadSet.Threads;
                DataBind();
            } 
            else {
                DataSource = null;
                DataBind();
            }

            #endregion

        }

        #endregion

        #region Public Properties

        /// <value>
        /// Total number of records to display
        /// </value>
        public int ForumID {
            get {
                return forumID;
            }
            set {
                forumID = value;
            }
        }

        /// <value>
        /// Total number of records to display
        /// </value>
        public int ItemsToDisplayCount {
            get {
                return itemsToDisplayCount;
            }
            set {
                itemsToDisplayCount = value;
            }
        }

        /// <value>
        /// Controls the mode that the thread view control displays
        /// </value>
        public ThreadViewMode ThreadViewMode {
            get {
                return mode;
            }
            set {
                mode = value;
            }
        }

		public DateTime ThreadsNewerThan
		{
			get { return threadsNewerThan; }
			set { threadsNewerThan = value; }
		}

		public SortThreadsBy SortThreadsBy
		{
			get { return sortBy; }
			set { sortBy = value; }
		}

		public SortOrder SortOrder
		{
			get { return sortOrder; }
			set { sortOrder = value; }
		}

        #endregion
    }

}
